package io.cici.cc.mybatis.lite.sql_source.scripting.ognl;

import io.cici.cc.mybatis.lite.util.SecurityManagerUtil;
import ognl.MemberAccess;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.util.Map;


/**
 * @author huihui
 */
public class MemberAccessImpl implements MemberAccess {

    private final boolean memberAccessibleControl;

    MemberAccessImpl() {
        this.memberAccessibleControl = SecurityManagerUtil.memberAccessibleControl();
    }

    @Override
    public Object setup(Map context, Object target, Member member, String propertyName) {
        Object result = null;
        if (isAccessible(context, target, member, propertyName)) {
            AccessibleObject accessible = (AccessibleObject) member;
            if (!accessible.isAccessible()) {
                result = Boolean.FALSE;
                accessible.setAccessible(true);
            }
        }
        return result;
    }

    @Override
    public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
        return memberAccessibleControl;
    }

    @Override
    public void restore(Map context, Object target, Member member, String propertyName, Object state) {
        // Flipping accessible flag is not thread safe. See #1648
    }


}
